#include <stdio.h>
#include "common.h"

static struct distance_table dt2;
static int me;

void printdt2(dtptr)
struct distance_table *dtptr;

{
    printf("                via     \n");
    printf("   D2 |    0     1    3 \n");
    printf("  ----|-----------------\n");
    printf("     0|  %3d   %3d   %3d\n",dtptr->costs[0][0],
           dtptr->costs[0][1],dtptr->costs[0][3]);
    printf("dest 1|  %3d   %3d   %3d\n",dtptr->costs[1][0],
           dtptr->costs[1][1],dtptr->costs[1][3]);
    printf("     3|  %3d   %3d   %3d\n",dtptr->costs[3][0],
           dtptr->costs[3][1],dtptr->costs[3][3]);
}



/* students to write the following two routines, and maybe some others */

void rtinit2() 
{
    me = 2;
    printf("Initialize dt%d\n", me);
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            dt2.costs[i][j] = 999;
        }
    }
    dt2.costs[2][1] = 1;
    dt2.costs[2][0] = 3;
    dt2.costs[2][3] = 2;
    dt2.costs[2][2] = 0;
    printTable(&dt2, me);

    send2Neighbors(&dt2, me);
}


void rtupdate2(rcvdpkt)
  struct rtpkt *rcvdpkt;
  
{
    int src = rcvdpkt->sourceid;
    for (int i = 0; i < 4; ++i) {
        dt2.costs[src][i] = rcvdpkt->mincost[i];
    }
    int needNotify = 0;
    for (int i = 0; i < 4; ++i) {
        if (i == me)
            continue;
        int minDist = 999;  // compute 0 -> i
        for (int j = 0; j < 4; ++j) { // via j
            if (dt2.costs[j][i] == 999) {
                continue;
            }
            minDist = min(minDist, dt2.costs[me][j] + dt2.costs[j][i]);
        }
        if (minDist < dt2.costs[me][i]) {
            dt2.costs[me][i] = minDist;
            // update the Dx(y) to neighbors
            needNotify = 1;
        }
    }

    if (needNotify) {
        printf("dt%d Updated:\n", me);
        send2Neighbors(&dt2, me);
    }
    printTable(&dt2, me);
}
